package com.cff.shorturl.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.cff.shorturl.util.Utils;

public class DruidDbManager extends DbManager {
	private DruidDataSource druidDataSource = null;

	protected DruidDbManager() {
		try {
			druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public Connection getConnection() throws SQLException {
		return druidDataSource.getConnection();
	}

	@Override
	public String queryString(Connection con, String sql, Object[] params) throws SQLException {
		PreparedStatement pre = null;
		try {
			pre = con.prepareStatement(sql);
			// 参数赋值
			if (params != null) {
				for (int i = 0; i < params.length; i++) {
					pre.setObject(i + 1, params[i]);
				}
			}
			ResultSet resultSet = pre.executeQuery();
			while (resultSet.next()) {
				String value = resultSet.getString(1);
				return value;
			}
		} catch (SQLException e) {
			throw e;
		} finally {
			try {
				if (pre != null)
					pre.close();
				if (con != null)
					con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public void execute(Connection con, String sql, Object... params) throws SQLException {
		PreparedStatement pre = null;
		try {
			pre = con.prepareStatement(sql);
			// 参数赋值
			if (params != null) {
				for (int i = 0; i < params.length; i++) {
					pre.setObject(i + 1, params[i]);
				}
			}
			// 执行
			pre.executeUpdate();
		} catch (SQLException e) {
			throw e;
		} finally {
			try {
				if (pre != null)
					pre.close();
				if (con != null)
					con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public int queryInt(Connection con, String sql, Object[] params) throws SQLException {
		PreparedStatement pre = null;
		try {
			pre = con.prepareStatement(sql);
			// 参数赋值
			if (params != null) {
				for (int i = 0; i < params.length; i++) {
					pre.setObject(i + 1, params[i]);
				}
			}
			ResultSet resultSet = pre.executeQuery();
			while (resultSet.next()) {
				int value = resultSet.getInt(1);
				return value;
			}
		} catch (SQLException e) {
			throw e;
		} finally {
			try {
				if (pre != null)
					pre.close();
				if (con != null)
					con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return -1;
	}

}
